package com.heima.article.interceptor;

import com.heima.article.utils.AppThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AppTokenInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 获取请求头
        String userId = request.getHeader("userId");

        //2. 存入线程
        if (StringUtils.isNotBlank(userId) && !StringUtils.equals("0", userId)) {
            AppThreadLocalUtil.setId(Long.valueOf(userId));
            return super.preHandle(request, response, handler);
        }

        //3.请求头为空
        return super.preHandle(request, response, handler);

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //清除线程
        AppThreadLocalUtil.remove();
        super.postHandle(request, response, handler, modelAndView);
    }
}
